package ide.ccf.ccdesigner.views.embedded;

import ide.ccf.ccproject.common.JambiCompatible;

import java.io.IOException;
import java.util.*;

import org.eclipse.swt.*;
import org.eclipse.swt.graphics.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.swt.events.*;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Platform;
import org.osgi.framework.Bundle;

/**
 * 设计器窗体窗口
 *
 */
public class FormWindowW extends Composite implements JambiCompatible
{
    long handleWidget;
    @SuppressWarnings("rawtypes")
	ArrayList listeners;
    @SuppressWarnings("rawtypes")
	static Hashtable table = new Hashtable();
    
    /**
     * 构造器
     * @param parent
     * @param style
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
	public FormWindowW(Composite parent, int style)
    {
        super (parent, style);
        
        try 
        {
            org.osgi.framework.Bundle bundle = org.eclipse.core.runtime.Platform.getBundle("ide.ccf.ccdesigner");
            
            if (bundle != null) 
            {
                Class cls = bundle.loadClass("ide.ccf.ccdesigner.cppjambi.QtJambiConnection");
                java.lang.reflect.Method m = cls.getMethod("validateJambi", new Class[] { JambiCompatible.class });
                m.invoke(null, new Object[] { this });
            }
        } 
        catch (Throwable t) 
        {
            Bundle pluginBundle = Platform.getBundle("ide.ccf.ccdesigner." + Platform.getOS() + "." + Platform.getOSArch());
            
            if (pluginBundle != null) 
            {
                try 
                {
                    String path = FileLocator.toFileURL(FileLocator.find(pluginBundle, new org.eclipse.core.runtime.Path("lib/libccfdesigner.so"), null)).getPath();
                    System.load(path);
                } 
                catch (IOException ex) 
                {
                    ex.printStackTrace();
                } 
                catch (UnsatisfiedLinkError ex) 
                {
                    ex.printStackTrace();
                }
            }
        }

        handleWidget = createControl(handle, embeddedHandle);
        
        if (handleWidget == 0) 
        	SWT.error (SWT.ERROR_NO_HANDLES);
        
        table.put(new Long(handleWidget), this);
        
        setFont(getFont());
    
        listeners = new ArrayList();

        addDisposeListener(new DisposeListener() 
        {
            public void widgetDisposed(DisposeEvent e) 
            {
                FormWindowW.this.widgetDisposed(e);
            }
        });

        addControlListener(new ControlAdapter() 
        {
            public void controlResized(ControlEvent e) 
            {
                FormWindowW.this.controlResized(e);
            }
        });

        try 
        {
            org.osgi.framework.Bundle bundle = org.eclipse.core.runtime.Platform.getBundle("ide.ccf.ccdesigner");
            
            if (bundle != null) 
            {
                Class cls = bundle.loadClass("ide.ccf.ccdesigner.cppjambi.QtJambiConnection");
                java.lang.reflect.Method m = cls.getMethod("loadPlugins", new Class[] { JambiCompatible.class });
                m.invoke(null, new Object[] { this });
            }
        } 
        catch (Throwable t) 
        {
        	
        }
        initialize();
    }

    /**
     * 装载库
     * 需要在一个类中调用，这个类将会被调用本地方法的同一个类装载器装载
     */
    public void loadLibrary(String path)
    {
        System.load(path);
    }
    
    /**
     * 释放
     * @param e
     */
    public void widgetDisposed (DisposeEvent e)
    {
        table.remove(new Long(handleWidget));
        disposeControl(handleWidget);
        handleWidget = 0;
    }
  
    /**
     * 重绘大小
     * @param e
     */
    public void controlResized(ControlEvent e)
    {
        Rectangle rect = getClientArea();
        resizeControl(handleWidget, rect.x, rect.y, rect.width, rect.height);
    }

    /**
     * 计算大小
     */
    public Point computeSize(int wHint, int hHint, boolean changed)
    {
        checkWidget();
        int [] result = new int[2];
        
        computeSize(handleWidget, result);
        
        if (wHint != SWT.DEFAULT) 
        	result[0] = wHint;
        
        if (hHint != SWT.DEFAULT) 
        	result[1] = hHint;
        
        int border = getBorderWidth();
        
        return new Point(result[0] + border * 2, result[1] + border * 2);
    }
    
    /**
     * 设置字体
     */
    public void setFont(Font font)
    {
        super.setFont(font);
        
        if (font == null)
            return;
        
        FontData[] fntlist = font.getFontData();
        setFont(handleWidget, fntlist[0].getName(), fntlist[0].getHeight());
    }
    
    /**
     * 插件失败信息
     */
    public String pluginFailureString()
    {
        checkWidget();
        return pluginFailureString(handleWidget);
    }

    /**
     * 打开设计文件
     * @param fileName
     */
    public void open(String fileName)
    {
        checkWidget();
        open(handleWidget, fileName);
    }

    /**
     * 保存
     * @return
     */
    public boolean save()
    {
        checkWidget();
        return save(handleWidget);
    }

    /**
     * 另存为
     * @param fileName
     * @return
     */
    public boolean saveAs(String fileName)
    {
        checkWidget();
        return saveAs(handleWidget, fileName);
    }

    /**
     * 内容是否过时
     * @return
     */
    public boolean isDirty()
    {
        checkWidget();
        return isDirty(handleWidget);
    }

    /**
     * 关闭
     */
    public void close()
    {
        checkWidget();
        close(handleWidget);
    }

    /**
     * 初始化
     */
    public void initialize()
    {
        checkWidget();
        initialize(handleWidget);
    }

    /**
     * 设置激活窗体窗口
     */
    public void setActiveFormWindow()
    {
        checkWidget();
        setActiveFormWindow(handleWidget);
    }

    /**
     * 设置对象名称
     * @param objectName
     */
    public void setObjectName(String objectName)
    {
        checkWidget();
        setObjectName(handleWidget, objectName);
    }

    /**
     * 初始化Jambi插件
     */
    public boolean initializeJambiPlugins(String jambiBase, String jambiPluginPath, String customWidgetClassPath, String resourcePath, String jvm)
    {
        checkWidget();
        return initializeJambiPlugins(handleWidget, jambiBase, jambiPluginPath, customWidgetClassPath, resourcePath, jvm);
    }

    /**
     * 更新Jambi资源路径
     * @param resourcePath
     */
    public void updateJambiResourcePath(String resourcePath)
    {
        checkWidget();
        updateJambiResourcePath(handleWidget, resourcePath);
    }

    /**
     * 更新自定义控件路径
     */
    public void updateCustomWidgetLocation(String path)
    {
        checkWidget();
        updateCustomWidgetLocation(handleWidget, path);
    }

    /**
     * 菜单操作数量
     * @return
     */
    public int actionCount()
    {
        checkWidget();
        return actionCount(handleWidget);
    }

    /**
     * 不可用菜单操作数量
     * @return
     */
    public int staticActionCount()
    {
        checkWidget();
        return staticActionCount(handleWidget);
    }

    /**
     * 菜单操作名称
     * @param id
     * @return
     */
    public String actionName(int id)
    {
        checkWidget();
        return actionName(handleWidget, id);
    }

    /**
     * 菜单操作提示
     * @param id
     * @return
     */
    public String actionToolTip(int id)
    {
        checkWidget();
        return actionToolTip(handleWidget, id);
    }

    /**
     * 切换
     * @param id
     */
    public void actionTrigger(int id)
    {
        checkWidget();
        actionTrigger(handleWidget, id);
    }

    /**
     * 是否可用
     * @param id
     * @return
     */
    public boolean isEnabled(int id)
    {
        checkWidget();
        return isEnabled(handleWidget, id);
    }

    /**
     * 工具数量
     * @return
     */
    public int toolCount()
    {
        checkWidget();
        return toolCount(handleWidget);
    }
    
    /**
     * 工具名称
     * @param index
     * @return
     */
    public String toolName(int index)
    {
        checkWidget();
        return toolName(handleWidget, index);
    }

    /**
     * 工具提示
     * @param index
     * @return
     */
    public String toolToolTip(int index)
    {
        checkWidget();
        return toolToolTip(handleWidget, index);
    }

    /**
     * 当前工具
     * @return
     */
    public int currentTool()
    {
        checkWidget();
        return currentTool(handleWidget);
    }

    /**
     * 设置当前工具
     * @param index
     */
    public void setCurrentTool(int index)
    {
        checkWidget();
        setCurrentTool(handleWidget, index);
    }

    /**
     * 添加窗体侦听器
     * @param lstnr
     */
    @SuppressWarnings("unchecked")
	public void addFormWindowWListener(FormWindowWListener lstnr)
    {
        listeners.add(lstnr);
    }

    /**
     * 删除窗体侦听器
     * @param lstnr
     */
    public void removeFormWindowWListener(FormWindowWListener lstnr)
    {
        listeners.remove(listeners.indexOf(lstnr));
    }

    /**
     * 菜单状态改变。本地回调函数
     * @param handle
     * @param id
     */
    static void actionChanged(long handle, int id)
    {
        FormWindowW obj = (FormWindowW) table.get(new Long (handle));
        
        if (obj == null) 
        	return;
        
        for (int i = 0; i < obj.listeners.size(); i++)
        {
            ((FormWindowWListener)obj.listeners.get(i)).actionChanged(id);
        }
    }

    /**
     * 确认激活窗口
     * @param handle
     */
    static void checkActiveWindow(long handle)
    {
        FormWindowW obj = (FormWindowW) table.get(new Long (handle));
        
        if (obj == null) 
        	return;
        
        for (int i = 0; i < obj.listeners.size(); i++)
        {
            ((FormWindowWListener)obj.listeners.get(i)).checkActiveWindow();
        }
    }

    /**
     * 资源文件改变
     * @param handle
     */
    static void resourceFilesChanged(long handle)
    {
        FormWindowW obj = (FormWindowW) table.get(new Long (handle));
        
        if (obj == null) 
        	return;
        
        for (int i = 0; i < obj.listeners.size(); i++)
        {
            ((FormWindowWListener)obj.listeners.get(i)).resourceFilesChanged();
        }
    }

    /**
     * 更新数据过时参数
     * @param handle
     */
    static void updateDirtyFlag(long handle)
    {
        FormWindowW obj = (FormWindowW) table.get(new Long (handle));
        
        if (obj == null) 
        	return;
        
        for (int i = 0; i < obj.listeners.size(); i++)
        {
            ((FormWindowWListener)obj.listeners.get(i)).updateDirtyFlag();
        }
    }
    
    /**
     * 转换动作名称到中文
     * @param name
     * @return
     */
    public String getNameByActionID(int actId, boolean isTip)
    {
    	switch (actId)
    	{
	    	case 0:
				return "剪切";
			
			case 1:
				return "复制";
				
			case 2:
				return "粘贴";
				
			case 3:
				return "删除";
				
			case 4:
				return "全选";
				
			case 5:
				return "撤销";
				
			case 6:
				return "重做";
				
    		case 7:
    			return "置后";
    		
    		case 8:
    			return "置前";
    			
    		case 9:
    			return "水平布局";
    			
    		case 10:
    			return "垂直布局";
    			
    		case 11:
    			return "使用分裂器水平布局";
    			
    		case 12:
    			return "使用分裂器垂直布局";
    			
    		case 13:
    			return "栅格排列";
    			
    		case 14:
    			return "取消布局";
    			
    		case 15:
    			return "调整大小";
    			
    		case 16:
    			return "预览";
    			
    		default:
    			if (isTip)
    				return actionToolTip(actId);
    				
    			else
    				return actionName(actId);			
    	}
    }

    static final native long createControl(long phandle, long socketWin);
    static final native void computeSize(long handle, int [] result);
    static final native void disposeControl(long handle);
    static final native void resizeControl(long handle, int x, int y, int width, int height);
    static final native void setFont(long handle, String family, int size);
    static final native String pluginFailureString(long handle);
    static final native void open(long handle, String fileName);
    static final native boolean save(long handle);
    static final native boolean saveAs(long handle, String fileName);
    static final native boolean isDirty(long handle);
    static final native void close(long handle);
    static final native void initialize(long handle);
    static final native void setActiveFormWindow(long handle);
    static final native void setObjectName(long handle, String objectName);
    static final native boolean initializeJambiPlugins(long handle, String jambiBase, String jambiPluginPath, String customWidgetClassPath, String resourcePath, String jvm);
    static final native void updateJambiResourcePath(long handle, String resourcePath);
    static final native void updateCustomWidgetLocation(long handle, String path);
    static final native int actionCount(long handle);
    static final native int staticActionCount(long handle);
    static final native String actionName(long handle, int id);
    static final native String actionToolTip(long handle, int id);
    static final native void actionTrigger(long handle, int id);
    static final native boolean isEnabled(long handle, int id);
    static final native int toolCount(long handle);
    static final native String toolName(long handle, int index);
    static final native String toolToolTip(long handle, int index);
    static final native int currentTool(long handle);
    static final native void setCurrentTool(long handle, int index);
}
